//
//  KQMessage.swift
//  JChat
//
//  Created by JIGUANG on 10/04/2017.
//  Copyright © 2017 HXHG. All rights reserved.
//

import UIKit
import KQChatSDK
import KakaJSON

open class KQMessage: NSObject, KQMessageType {
    

    init(content: KQMessageContentType) {
        self.content = content
        self.options = KQMessageOptions(with: content)
        super.init()
    }
    
    public let identifier: UUID = .init()
    open var msgId = ""
    open var name: String = "UserName"
    open var date: Date = .init()
    open var sender: WFCCUserInfo?
    open var senderAvator: UIImage?
    open var receiver: WFCCUserInfo?
    open var content: KQMessageContentType
    public let options: KQMessageOptions
    open var updateSizeIfNeeded: Bool = false
    open var unreadCount: Int = 0
    open var targetType: MessageTargetType = .single
    open var jmessage: WFCCMessage?
}

extension WFCCMessage {
    typealias Callback = (WFCCMessage, Data?) -> Void
    func parseMessage(_ delegate: KQMessageDelegate, _ updateMediaMessage: Callback? = nil) -> KQMessage {
        var msg: KQMessage!
        let savedUserId = UserDefaults.standard.value(forKey: "savedUserId") as? String

        let currentUser = WFCCIMService.sharedWFCIM().getUserInfo(savedUserId, refresh: false)
        let isCurrent = fromUser.isEqual(currentUser)
        
        
        
        
        if self.content.isKind(of: WFCCTextMessageContent.self) {
            /// 文本
            let content = self.content as! WFCCTextMessageContent
            let textContent = KQMessageTextContent(text: content.text)
            textContent.delegate = delegate
            msg = KQMessage(content: textContent)
        } else if self.content.isKind(of: WFCCSoundMessageContent.self){
            /// 录音
            let messageContent = self.content as! WFCCSoundMessageContent
            let voiceContent = KQMessageVoiceContent()
            voiceContent.duration = TimeInterval(messageContent.duration)
            voiceContent.data = messageContent.getWavData()
            voiceContent.delegate = delegate
            msg = KQMessage(content: voiceContent)
        } else if self.content.isKind(of: WFCCImageMessageContent.self){
            /// 图片
            let content = self.content as! WFCCImageMessageContent
            let imageContent = KQMessageImageContent()
            imageContent.imageSize = content.thumbnail.size
            
            imageContent.delegate = delegate
            msg = KQMessage(content: imageContent)
            if content.size != .zero {
                imageContent.imageSize = content.size
            } else if content.thumbnail.size != .zero {
                imageContent.imageSize = content.thumbnail.size
            } else {
                imageContent.imageSize = CGSize.init(width: 140, height: 140)
            }
            imageContent.thumbnailImage = content.thumbnail
            imageContent.remoteUrl = content.remoteUrl
            
        } else if self.content.isKind(of: WFCCVideoMessageContent.self) {
            printLog("video message")
            let content = self.content as! WFCCVideoMessageContent
            let videoContent = KQMessageVideoContent()
            videoContent.delegate = delegate
            
            if status == .Message_Status_Sending {
                videoContent.uploadVideo?(0)
            }
            videoContent.image = content.thumbnail

            msg = KQMessage(content: videoContent)
                
        } else if self.content.isKind(of: WFCCStickerMessageContent.self){
            let content = self.content as! WFCCStickerMessageContent
            let imageContent = KQMessageImageContent()
            imageContent.imageSize = CGSize(width: content.size.width / 3, height: content.size.height / 3)
            
            imageContent.delegate = delegate
            msg = KQMessage(content: imageContent)
            if let path = content.localPath {
                let image = UIImage(contentsOfFile: path)
                imageContent.thumbnailImage = image
                msg.content = imageContent
            } else {
                if let url = URL(string: content.remoteUrl) {
                    let d = try? Data.init(contentsOf: url)
                    updateMediaMessage!(self, d)
                }
            }
        } else if self.content.isKind(of: WFCCCardMessageContent.self){
            let content = self.content as! WFCCCardMessageContent
            let businessCardContent = KQBusinessCardContent()
            businessCardContent.delegate = delegate
            businessCardContent.appKey = content.targetId
            businessCardContent.userName = content.displayName
            msg = KQMessage(content: businessCardContent)
        }  else if self.content.isKind(of: WFCCNotificationMessageContent.self){
            let content = self.content as! WFCCNotificationMessageContent
            let noticeContent = KQMessageNoticeContent(text: content.formatNotification(self))
            msg = KQMessage(content: noticeContent)
            msg.options.showsTips = false
            msg.options.alignment = .center
        }  else {
            msg = KQMessage(content: KQMessageNoticeContent.unsupport)
        }
        if msg.options.alignment != .center {
            if direction == .MessageDirection_Send {
                msg.options.alignment = .right
            } else {
                msg.options.alignment = .left
            }
        }

        msg.targetType = MessageTargetType(rawValue: self.conversation.type.rawValue + 1)!
        msg.msgId = "\(self.messageId)"
        if self.status == .Message_Status_Sending {
            msg.options.state = .sending
        } else if self.status == .Message_Status_Send_Failure {
            msg.options.state = .sendError
        } else if self.status == .Message_Status_Sent {
            msg.options.state = .sendSucceed
        }
        if isCurrent {
            msg.senderAvator = UIImage.getMyAvator()
        }
        let fromUser = WFCCIMService.sharedWFCIM().getUserInfo(self.fromUser, refresh: false)
        msg.sender = fromUser
        msg.name = fromUser?.displayName ?? ""
        msg.jmessage = self
        return msg
    }
}
